/**
 * 
 */
package sort.result;

import java.lang.management.ManagementFactory;

import sort.CheckUtil;
import sort.record.Records;

/**
 * @author masaru-gotou
 *
 */
public class SortResultWatcher {
	private Records before_sort = null;
	private SortResult result = null;
	private long start_time;
	private long start_used_mem;
	private String algoname;
	
	public SortResultWatcher(String algoname ) {
		this.algoname = algoname;
	}
	
	public void start(Records before_sort) {
		this.before_sort = before_sort;
		start_time = System.currentTimeMillis();
		start_used_mem = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
	}
	public void finish(Records after_sort) {
		if ( before_sort == null ) throw new IllegalStateException("not started");
		long end_time = System.currentTimeMillis();
		long end_used_mem = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
		result = new SortResult();
		result.setAlgorithmName(algoname);
		result.setElapsedTime(end_time - start_time);
		result.setValidated(CheckUtil.isSame(before_sort, after_sort) );
		result.setRecordCount(before_sort.size());
		result.setSorted(CheckUtil.isSorted(after_sort));
		result.setStabled(CheckUtil.isStabled(before_sort, after_sort));
		result.setUsedMemory( end_used_mem - start_used_mem);
		result.setSortedRecords(after_sort);
	}
	public SortResult getResult() {
		if ( result == null ) throw new IllegalStateException("not finished");
		return result;
	}
	
}
